package com.learn.hibernatevalidator.chapter02.containerelement.custom;

import jakarta.validation.Constraint;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import jakarta.validation.Payload;

import java.lang.annotation.*;

/**
 * @author: liyf
 * @create: 2024-12-21 20:41
 **/

@Documented
@Constraint(validatedBy = MinTorque.MinTorqueValidator.class)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MinTorque {

    long value();

    String message() default "{org.hibernate.validator.referenceguide.chapter02.containerelement.MinTorque.message}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};


    class MinTorqueValidator implements ConstraintValidator<MinTorque, Gear> {

        private long min;


        @Override
        public void initialize(MinTorque constraintAnnotation) {
            this.min = constraintAnnotation.value();
        }

        @Override
        public boolean isValid(Gear gear, ConstraintValidatorContext constraintValidatorContext) {
            if (gear == null) {
                return true;
            }

            return gear.getTorque() > min;
        }
    }
}
